﻿using System;
using System.Linq;
using StreetPacMan.Server.Facade;

namespace StreetPacMan.Server.Rules.PlayerLocationChangeRules
{
    public class AddPollingEventRule : IHandlePlayerLocationChangedRule
    {
        public void Handle(PacManDataContext dataContext, ServerPollParameters serverPollParameters, ref bool shouldContinueHandling)
        {
            var player = dataContext.Players.Where(x => x.Id == serverPollParameters.EntityId).Single();

            var locationChganged = player.LastGeoLat != serverPollParameters.GeoLat ||
                                   player.LastGeoLon != serverPollParameters.GeoLng;
            string description = locationChganged
                                     ? string.Format("{0} polled server at ({1},{2})", player.Name,
                                                     serverPollParameters.GeoLat, serverPollParameters.GeoLng)
                                     : player.Name + " polled server (same location)";

            dataContext.Events.InsertOnSubmit(new Event
                                                  {
                                                      ReceivedAt = DateTime.Now,
                                                      TypeEnum = EventType.PlayerPolledServer,
                                                      GameId = player.GameId,
                                                      Description = description
                                                  });
        }
    }
}